// <div data-user-id="42"></div>
// const userId = element.dataset.userId; // "42"
// chatContainer.dataset.roomId = "456";
// 读取data数据的方式HTML 中 data-xxx-yyy → JS 中 dataset.xxxYyy
document.addEventListener('DOMContentLoaded', () => {
    const container = document.getElementById('chat-container');
    const room_id = container.dataset.roomId;
    const message = document.getElementById('msg');
    const deepseek = document.getElementById('deepseek-check');
    const sendButton = document.getElementById('send');
    const messageList = document.getElementById('chat-messages');


    const chatSocket = new WebSocket(`ws://ws/chat/${room_id}/`);
    chatSocket.onopen = ()=>console.log("websocket已连接");
    chatSocket.onmessage=(e)=>{
        const data = JSON.parse(e.data)
        let p = document.createElement("p");
        if  (data.type == "system_message") {
            p.innerHTML = `<em>${data.sender}: ${data.message} (${data.timestamp})`;
        }
        else if (data.type=="chat_message"){
            if (data.is_deepseek){
                p.innerHTML = `<em>${data.sender}: ${data.message} (${data.timestamp})`;
            }
            p.innerHTML = `<em>${data.sender}: ${data.message} (${data.timestamp}) (${data.require_deepseek})`;
        }
        messageList.append(p);
        messageList.scrollTop = messageList.scrollHeight;
    }
    chatSocket.onclose=(e)=>console.log("websocket断开连接",e);
    sendButton.addEventListener("click",()=>{
        let msg = message.value.trim();
        if (msg) {
            chatSocket.send(
                JSON.stringify({
                    message:msg,
                    require_deepseek:deepseek.checked
                })
            )
            message.value = "";
            deepseek.checked = false;
        }
    })
})